package handler

import (
	"github.com/gin-gonic/gin"
	"novel-mng/cache"
	"novel-mng/kpg"
	"novel-mng/model"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "参数不能为空",
		})
		return
	}
	var user model.User
	redis_key := "login_" + username
	errConfig, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errConfig > 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次,禁止登录",
		})
		return
	}
	err := model.DB.Where("username=?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查找失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != kpg.Wd5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errConfig == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": "500",
				"msg":  "密码错误三次,封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": "500",
			"msg":  "密码错误",
		})
		return
	}
	token := kpg.TokenHandler(int(user.ID))
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "登录成功",
		"token": token,
		"data":  user,
	})
	return
}
